package services.image;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import play.Logger;
import play.libs.WS;
import play.libs.WS.HttpResponse;
import services.image.ImageSearchService.ImageExt;
import controllers.Data;

public class GoogleImageService implements ImageSearchService {

	private static final String searchPattern = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s&start=%s&rsz=%s";
	
	@Override
	public Data<ImageExt> search(String terms, int offset, int limit) throws IOException {
		Data<ImageExt> images = new Data<ImageExt>();
		images.total = 0;
		images.data = new ArrayList<ImageExt>();
		if(limit>8) limit=8;
		HttpResponse response = WS.url(searchPattern, terms, ""+offset, ""+limit).get();
		if( response.getStatus() == 200 ) {
			Reader reader = new InputStreamReader(response.getStream());
			JsonObject jsobj = new JsonParser().parse(reader).getAsJsonObject();
			StringBuilder sb = new StringBuilder();
		    String line;
		    BufferedReader r1 = new BufferedReader(new InputStreamReader(response.getStream(), "UTF-8"));
		    while ((line = r1.readLine()) != null) {
		    	sb.append(line).append("\n");
		    }
		    //System.out.println(sb.toString());
		    if(jsobj.get("responseData").isJsonNull()) {
		    	images.total = 0;
		    } else {
		    	Long estimatedTotal = jsobj.get("responseData").getAsJsonObject().get("cursor").getAsJsonObject().get("estimatedResultCount").getAsLong();
		    	if(estimatedTotal<50)
		    		images.total = estimatedTotal.intValue();
		    	else
		    		images.total = 50;
		    	Iterator<JsonElement> eleIt = jsobj.get("responseData").getAsJsonObject().get("results").getAsJsonArray().iterator();
		    	while(eleIt.hasNext()) {
					JsonObject imageJson = eleIt.next().getAsJsonObject();
					ImageExt image = new ImageExt();
					image.title = imageJson.get("titleNoFormatting").getAsString();
					image.original = imageJson.get("url").getAsString();
					image.thumbnail = imageJson.get("tbUrl").getAsString();
					images.data.add(image);
				}
		    }

			//Logger.info("Result count %s", jsobj.get("responseData").getAsJsonObject().get("cursor").getAsJsonObject().get("estimatedResultCount").getAsInt());
		}
		return images;
	}

}
